import Log = require('../common/RunLog');
import { deprecate } from 'util';
import { logtypedef } from '../common/RunLog';
import WebConstant from '../common/WebConstant';

export default class CommonFunc{
    public static checkClientIP(req:any):boolean{
        try
        {
            let ipaddr =  CommonFunc.getClientIp(req);
            if(!ipaddr){
                return false;
            }
            let ipArray = ipaddr.split(":");
    
            for(let i=0; i < ipArray.length; i++){
                if(ipArray[i].length <= 1){
                    continue;
                }
                if( ipArray[i] == "127.0.0.1" || 
                    ipArray[i].substr(0, 7) == "192.168"){
                        return true;
                    }
            }
        }
        catch(ex) {
            Log.default.addlog("获取不到IP地址, from page = "+req.params[0], logtypedef.LOG_TYPE_EXCEPTION);
        }
        return false;
    }

    public static formatDate(datetime:any, format:string):string
    {
        let o : {[key:string]:any} = {
            "M+" : datetime.getMonth()+1, //month
            "d+" : datetime.getDate(), //day
            "h+" : datetime.getHours(), //hour
            "m+" : datetime.getMinutes(), //minute
            "s+" : datetime.getSeconds(), //second
            "q+" : Math.floor((datetime.getMonth()+3)/3), //quarter
            "S" : datetime.getMilliseconds() //millisecond
        }
        if(/(y+)/.test(format)) 
        format=format.replace(RegExp.$1,(datetime.getFullYear()+"").substr(4- RegExp.$1.length));
        for(let k in o){
            if(new RegExp("("+ k +")").test(format))
            {
                let v = 
                format = format.replace(RegExp.$1,RegExp.$1.length==1? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
            }
        }
            
        return format;
    }

    public static getClientIp(req:any):string{
        try{
            var ipaddr =  req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress;

            return ipaddr;
        }
        catch(ex){
            return "";
        }
    }

    public static getRootkey(appid:string, roomid:string){
        return appid+"#_#"+roomid;
    }

    public static  makeParamString(appid:string, roomid:string, openid?:string, clientid?:string){
        let str = " appid="+appid+", roomid="+roomid+" ";
        if(openid){
            str+=", openid="+openid;
        }
        if(clientid){
            str+= ", client="+clientid;
        }
        return str;
    }
    
    public static getRootUserPath(currentUser:string):string{
        let userPath = currentUser == "admin" ? "" : currentUser + "/";
        let defaultPath = WebConstant.UPLOAD_PATH + userPath;

        return defaultPath;
    }
}